package bsh.dyn;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.objectweb.asm.MethodVisitor;

import bsh.CompilationState;
import bsh.CompilationUnit;
import bsh.CompiledScript;
import bsh.exception.CompilationFailedException;

/**
 * Invocable that represents a constructor and uses reflection to call the constructor. This is not compilable, but the
 * {@link AdaptedInvocable} can be used instead
 * 
 * @author takeshi
 */
public class ConstructorInvocable implements Invocable {

    private final Constructor<?> constructor;

    /**
     * C'tor
     * 
     * @param constructor the constructor
     */
    public ConstructorInvocable(Constructor<?> constructor) {
        super();
        this.constructor = constructor;
    }

    /**
     * {@inheritDoc}
     */
    public Object invoke(CompiledScript script, Object target, Object[] parameters) throws Throwable {
        try {
            return this.constructor.newInstance(parameters);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    }

    /**
     * {@inheritDoc}
     */
    public DeclaredParameterType[] getParameterTypes() {
        return Invocables.toDeclaredParameters(this.constructor.getParameterTypes());
    }

    /**
     * {@inheritDoc}
     */
    public boolean isVarargs() {
        return this.constructor.isVarArgs();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return this.constructor.toString();
    }

    /**
     * {@inheritDoc}
     */
    public boolean isCompilable() {
        return false;
    }

    /**
     * @return the {@link Constructor}
     */
    public Constructor getConstructor() {
        return this.constructor;
    }

    /**
     * {@inheritDoc}
     */
    public void generateBytecode(MethodVisitor visitor, CompilationUnit unit, CompilationState state) throws CompilationFailedException {
        throw new IllegalStateException("cannot be compiled");
    }

}
